import axios from "axios";
import {getToken} from "@/utils/auth";
import { Notification } from 'element-ui'

export function axiosDownload({params,data,type,url,method}){
  axios({
    method: method,
    url: process.env.VUE_APP_BASE_API+url,
    responseType: 'blob',
    params:params||{},
    data:method==='post'?data:{},
    headers: { 'Authorization': 'Bearer ' + getToken() }
  }).then(res => {
    download(res,type)
  }).catch(err =>{
    console.error(err)
    Notification({
      title:'下载异常',
      message: 'Error',
      type: 'error',
      duration: 5 * 1000
    })

  })
}


export function download(res,type){
  const aLink = document.createElement('a')
  let blob = new Blob([res.data], { type: type })
  let pattern = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  let contentDisposition = decodeURI(res.headers['content-disposition'])
  let result = pattern.exec(contentDisposition)
  let fileName = result[1]
  fileName = fileName.replace(/\"/g, '')
  aLink.style.display = 'none'
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  URL.revokeObjectURL(aLink.href);//清除引用
  document.body.removeChild(aLink);
}
